package com.zhouzhou.fastjava.criteria;

import com.zhouzhou.fastjava.provider.IPProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class SpringMVCIPProvider implements IPProvider {

    private final String headerKey;

    public SpringMVCIPProvider() {
        this(null);
    }

    public SpringMVCIPProvider(String headerKey) {
        super();
        this.headerKey = headerKey;
    }

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }

    @Override
    public String getIP() {
        String ip = "Unknown";
        HttpServletRequest request = getRequest();
        try {
            if (headerKey != null) {
                ip = request.getHeader(headerKey);
            }
            if (StringUtils.isBlank(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            // skip
        }
        return ip;
    }

}
